//
//  ViewController.m
//  Footer
//
//  Created by leotao on 16/12/17.
//  Copyright © 2016年 leotao. All rights reserved.
//

#import "ViewController.h"
#import "MJRefresh.h"
#import "RefreshHeader.h"
#import "RefreshFooter.h"
#import "CustomCell.h"
#import "MJRefreshCircleHeader.h"
#import "RTCircleHeader.h"
#import "Masonry.h"
#import "CircleView.h"

#define kUseMJFooter 1

#define RGB(r,g,b) [UIColor colorWithRed: r / 255.0 green: g / 255.0 blue: b / 255.0 alpha:1.0]

@interface ViewController () <UITableViewDelegate, UITableViewDataSource>

@property (strong, nonatomic) UITableView *tableView;
@property (assign, nonatomic) NSInteger page;
@property (assign, nonatomic) NSInteger dataCount;
@property (strong, nonatomic) UIPanGestureRecognizer *panGesture;
@property (strong, nonatomic) RefreshHeader *header;
@property (strong, nonatomic) RefreshFooter *footer;
@property (assign, nonatomic) UIEdgeInsets originalInsets;
@property (strong, nonatomic) CircleView *circleView;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    
    [self commonSetup];
    [self setupTableView];

#if kUseMJFooter
    [self setupFooter];
#endif

}

- (void)commonSetup
{
    [self.navigationController.navigationBar setBarTintColor:RGB(0, 138, 228)];
    
//    CircleView *circleView = [[CircleView alloc] init];
//    circleView.frame = CGRectInset(self.view.bounds, 100, 250);
//    [self.view addSubview:circleView];
//    
//    self.circleView = circleView;
}

- (void)setupTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.dataCount = 5;
    self.tableView.backgroundColor = RGB(242, 244, 247);
    self.tableView.estimatedRowHeight = 88.0;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.view addSubview:self.tableView];
    
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];

#if kUseMJFooter == 0
    [self setupCustomFooter];
#endif
    
}

- (void)setupCustomFooter
{
    self.originalInsets = self.tableView.contentInset;
    NSLog(@"self.originalInsets = %@", NSStringFromUIEdgeInsets(self.originalInsets));
    RefreshFooter *footer = [[RefreshFooter alloc] init];
    self.footer = footer;
    [self.tableView insertSubview:footer atIndex:0];
    
    RefreshHeader *header = [[RefreshHeader alloc] init];
    self.header = header;
    [self.tableView insertSubview:header atIndex:0];
    
    self.navigationController.navigationBar.translucent = NO;
    
    self.panGesture = self.tableView.panGestureRecognizer;
    
    [self.panGesture addObserver:self forKeyPath:@"state" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    [self.tableView addObserver:self forKeyPath:@"contentSize" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    
//     NSLog(@"self.originalInsets = %@", NSStringFromUIEdgeInsets(self.tableView.contentInset));
}

- (void)setupFooter
{
    __weak typeof(self)weakSelf = self;
    self.tableView.mj_footer = [MJRefreshBackStateFooter footerWithRefreshingBlock:^{
        if (weakSelf.page < 10) {
            [weakSelf loadMoreData];
        } else {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [weakSelf.tableView.mj_footer endRefreshingWithNoMoreData];
            });
        }
    }];
    
    self.tableView.mj_header = [RTCircleHeader headerWithRefreshingBlock:^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [weakSelf.tableView reloadData];
            [weakSelf.tableView.mj_header endRefreshing];
        });
    }];
    
    CGRect rect = self.tableView.mj_header.frame;
    rect.size.height *= 2;
    rect.origin.y -= rect.size.height;
    self.tableView.mj_header.frame = rect;
    
//    ((MJRefreshAutoNormalFooter *)self.tableView.mj_footer).triggerAutomaticallyRefreshPercent = 0;
    

    
    
    
}

- (void)loadMoreData
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
         [self.tableView.mj_footer endRefreshing];
        self.dataCount += 5;
        self.page++;
        [self.tableView reloadData];
        
    });
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.dataCount;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"test";
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (!cell) {
        cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    
    NSInteger num = arc4random() % 100;
    [cell configureCell:num];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    CustomCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    NSLog(@"%@", cell);
}



- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"state"]) {
        [self handleStateChange:change];
    } else if ([keyPath isEqualToString:@"contentSize"]) {
        [self handleContentSizeChange:change];
    }
}

- (void)handleStateChange: (NSDictionary *)change
{
    NSLog(@"offSet = %f footer.frame = %@", CGRectGetMaxY(self.tableView.bounds), NSStringFromCGRect(self.footer.frame));
    self.originalInsets = self.tableView.contentInset;
    if (self.panGesture.state == UIGestureRecognizerStateEnded) {   // 拖拽停止
        if (self.tableView.contentOffset.y <= -self.header.frame.size.height-self.originalInsets.top && self.header.state == RefreshStateIdle) {
            NSLog(@"before self.originalInsets = %@", NSStringFromUIEdgeInsets(self.originalInsets));
            [UIView animateWithDuration:0.33 animations:^{
                self.tableView.contentInset = UIEdgeInsetsMake(self.header.frame.size.height + self.originalInsets.top, 0, 0, 0);
            }];
            
            [self.header beginRefresh];
            NSLog(@"开始刷新==========");
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [UIView animateWithDuration:0.33 animations:^{
                    self.tableView.contentInset = self.originalInsets;
                    NSLog(@"after self.originalInsets = %@", NSStringFromUIEdgeInsets(self.originalInsets));
                }];
                
                [self.tableView reloadData];
                [self.header endRefrsh];
                NSLog(@"结束刷新==========");
            });
        } else if ( CGRectGetMaxY(self.tableView.bounds) > CGRectGetMaxY(self.footer.frame) && self.footer.state == RefreshStateIdle) {    // 上拉
            
            
            [UIView animateWithDuration:0.33 animations:^{
                self.tableView.contentInset = UIEdgeInsetsMake(0, 0, self.originalInsets.bottom + self.footer.frame.size.height, 0);
            }];
            
            [self.footer beginRefresh];
            NSLog(@"开始刷新==========");
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.dataCount += 10;
                self.page++;
                
                
                
               
                [self.footer endRefrsh];
                NSLog(@"结束刷新==========");
                
                [UIView animateWithDuration:1.4 animations:^{
                    self.tableView.contentInset = self.originalInsets;
                    NSLog(@"after self.originalInsets = %@", NSStringFromUIEdgeInsets(self.originalInsets));
                }];
                
                 [self.tableView reloadData];
            });
            
        }
    }
}

- (void)handleContentSizeChange: (NSDictionary *)change
{
    CGFloat contentHeight = self.tableView.contentSize.height;
    CGFloat scrollHeight = self.tableView.frame.size.height - self.tableView.contentInset.top - self.tableView.contentInset.bottom;
    CGFloat y = MAX(contentHeight, scrollHeight);
    self.footer.frame = CGRectMake(0, y, self.tableView.contentSize.width, 64);
    self.header.frame = CGRectMake(0, -88, self.tableView.contentSize.width, 88);
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    
    [UIView animateWithDuration:10 animations:^{
        self.circleView.progress = 0.8;
    }];
}

@end
